/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes.resources;

import com.google.inject.Inject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import net.sourceforge.stripes.action.ErrorResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.ValidationError;
import net.sourceforge.stripes.validation.ValidationErrors;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import th.config.ableContextListener;

import th.manager.AkaunFavManager;
import th.manager.AkaunManager;
import th.manager.SMSgatewayManager;
import th.manager.UserManager;
import th.model.Akaun;
import th.model.AkaunFav;
import th.model.Deposit;
import th.model.InfoAudit;
import th.model.KodJantina;
import th.model.KodKahwin;
import th.model.KodKebenaranTransaksi;
import th.model.KodNegeri;
import th.model.KodPekerjaan;
import th.model.KodSektorPekerjaan;
import th.model.KodWarganegara;
import th.model.Pengguna;
import th.model.PenyataAkaun;
import th.model.PenyataKad;
import th.model.Poskod;
import th.service.session.LoginSession;
import th.service.session.SessionManager;
import th.stripes.BaseActionBean;
import th.stripes.action.DepositActionBean;
import th.stripes.action.TransferDepositAction;
import th.stripes.services.DepositService;
import th.stripes.util.AccCheckUtil;

/**
 *
 * @author fikri
 */
@UrlBinding("/services/deposit")
public class DepositResource extends BaseActionBean implements iRest {

     private Deposit deposit;
     private String status;
     private static final Logger LOG = Logger.getLogger(DepositService.class);

     @Inject
     private UserManager userManager;

     @Inject 
    private KodNegeri kodNegeri;
     
    @Inject
    private KodJantina kodJantina;
    
    @Inject
    private KodKahwin kodKahwin;
    
    @Inject
    private Poskod poskod;
    
    @Inject
    private KodPekerjaan kodPekerjaan;
    
    @Inject
    private KodSektorPekerjaan kodSektorPekerjaan;
    
    @Inject
    private KodWarganegara kodWarganegara;

     @Inject
     private AkaunManager akaunManager;

     @Inject
     private SMSgatewayManager sMSgatewayManager;

     @Inject
     private AkaunFavManager akaunFavManager;

     private static final String HEADER_ID_FND_TFR = "THSTHT3";
     
     @HandlesEvent("up_profile")
    public Resolution updateProfile() throws ParseException {

//        LOG.debug("requestEntity : " +  deposit != null ? deposit.getNoAkaun(): "null" );      
        String line = null;
        
        StringBuilder sb = new StringBuilder();
        
        String id = getContext().getRequest().getHeader("Cookie");    
        id = id.substring(id.indexOf("=")+1);
        
        BufferedReader reader = null;
        try {
            
            reader = getContext().getRequest().getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            if (sb.length() > 0) {
                JSONObject json = new org.json.JSONObject(sb.toString());
                DepositService service = ableContextListener.newInstance(DepositService.class);
                deposit = new Deposit();
                deposit.setNoAkaun( json.getString("noAkaun") != null ?  json.getString("noAkaun") : null);
                deposit.setNoKp( json.getString("noKP") != null ?  json.getString("noKP") : null );
                deposit.setNoAkaunDari(json.getString("noAkaunDari") != null ?  json.getString("noAkaunDari") : null);
                deposit.setNoKpDari(json.getString("noKPDari") != null ?  json.getString("noKPDari") : null );
                
                 AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
        
                 boolean check = checking.checkAcc(deposit, id);
                 
                 if (!check) {
                     return new ErrorResolution(401);
                 }                
                
                String idSessi = getContext().getRequest().getSession().getId();
                
                service.depositorProfile(deposit, checking.getPengguna(), status, idSessi);
                
                
                return new StreamingResolution("application/json", toJsonUpProfile());
            }
            
            
        } catch (IOException e) { 
            LOG.error(e);
            
        }finally{
            try {
                if (reader != null) reader.close();
            } catch (IOException ex) {
                
            }
        }

        return new ErrorResolution(401);
    }
    
    @HandlesEvent("save_profile")
    public Resolution saveProfile() {

//        LOG.debug("requestEntity : " +  deposit != null ? deposit.getNoAkaun(): "null" );      
        String line = null;
        
        StringBuilder sb = new StringBuilder();
        String cookie = getContext().getRequest().getHeader("Cookie");
          String id = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));
          String idSessi = cookie.substring(cookie.indexOf(":") + 1);
          
//        String id = getContext().getRequest().getHeader("Cookie");    
//        id = id.substring(id.indexOf("=")+1);
        
        BufferedReader reader = null;
        try {
            
            reader = getContext().getRequest().getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            if (sb.length() > 0) {
                JSONObject json = new org.json.JSONObject(sb.toString());
                DepositService service = ableContextListener.newInstance(DepositService.class);
                
                deposit = new Deposit();
                deposit.setNoAkaun      (json.getString("noAkaun")      != null ?  json.getString("noAkaun")    : null);
                deposit.setNoKp         (json.getString("noKP")         != null ?  json.getString("noKP")       : null );
                deposit.setNoAkaunDari  (json.getString("noAkaunDari")  != null ?  json.getString("noAkaunDari"): null);
                deposit.setNoKpDari     (json.getString("noKPDari")     != null ?  json.getString("noKPDari")   : null );
                
                AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
        
                 boolean check = checking.checkAcc(deposit, id);
                 
                 if (!check) {
                     return new ErrorResolution(401);
                 }                
                
  //              String idSessi = getContext().getRequest().getSession().getId();
                
                deposit.setNama         (json.getString("nama")         != null ?  json.getString("nama")       : null );
                deposit.setEmail        (json.getString("email")        != null ?  json.getString("email")      : null );
                deposit.setNamaDatuk    (json.getString("namaIbu")      != null ?  json.getString("namaIbu")    : null );
                deposit.setAlamat1      (json.getString("alamat1")      != null ?  json.getString("alamat1")    : null );
                deposit.setAlamat2      (json.getString("alamat2")      != null ?  json.getString("alamat2")    : null );
                deposit.setAlamat3      (json.getString("alamat3")      != null ?  json.getString("alamat3")    : null );
                deposit.setAlamat4      ("Pahang");//json.getString("alamat4")      != null ?  json.getString("alamat4")    : null );
                deposit.setPoskod       (json.getString("poskod")       != null ?  json.getString("poskod")     : null );
                deposit.setNoTel1       (json.getString("noTel1")       != null ?  json.getString("noTel1")     : null );
                deposit.setNoTel2       (json.getString("noTel2")       != null ?  json.getString("noTel2")     : null );
                deposit.setNoTel3       (json.getString("noTel3")       != null ?  json.getString("noTel3")     : null );
                deposit.setTacNumber    (json.getString("tac")          != null ?  json.getString("tac")        : null );
                deposit.setBangsa       (json.getString("bangsa")       != null ?  json.getString("bangsa")     : null );
                try {
                deposit.setTarikhLahir  (json.getString("tLahirFinal")       != null ?  new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(json.getString("tLahirFinal"))     : null );
                } catch (ParseException ex) {
                    java.util.logging.Logger.getLogger(DepositResource.class.getName()).log(Level.SEVERE, null, ex);
                }
                kodNegeri.setCode       (json.getString("negeri")       != null ?  json.getString("negeri")     : null );
                deposit.setNegeri       (kodNegeri);
                //state
                kodSektorPekerjaan.setKod     (json.getString("pekerjaan")    != null ?  json.getString("pekerjaan")  : null );
                deposit.setSektorPekerjaan(kodSektorPekerjaan);
                //employ
                kodJantina.setKod       (json.getString("jantinaKodFinal") );
                deposit.setJantina      (kodJantina);
                //gender
                //ethinic
                kodKahwin.setKod        (json.getString("kahwin")       != null ?  json.getString("kahwin")     : null );
                deposit.setKahwin       (kodKahwin);
                //marital
                kodWarganegara.setKod   (json.getString("wargaKodFinal"));
                deposit.setWarganegara  (kodWarganegara);
                //nationality
                
                
                service.saveDepositorProfile(deposit, checking.getPengguna(), status, idSessi);
                
                return new StreamingResolution("application/json", toJson());
            }
            
            
        } catch (IOException e) { 
            LOG.error(e);
            
        }finally{
    
            try {
                if (reader != null) reader.close();
            } catch (IOException ex) {
                System.out.println("Error : "+ex);
            }
        }

        return new ErrorResolution(401);
    }
    
    

     @HandlesEvent("req_balance")
     public Resolution checkBalance() {

//        LOG.debug("requestEntity : " +  deposit != null ? deposit.getNoAkaun(): "null" );      
          String line = null;

          StringBuilder sb = new StringBuilder();

          String id = getContext().getRequest().getHeader("Cookie");
          id = id.substring(id.indexOf("=") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {
                    JSONObject json = new org.json.JSONObject(sb.toString());
                    DepositService service = ableContextListener.newInstance(DepositService.class);
                    deposit = new Deposit();
                    deposit.setNoAkaun(json.getString("noAkaun") != null ? json.getString("noAkaun") : null);
                    deposit.setNoKp(json.getString("noKP") != null ? json.getString("noKP") : null);
                    deposit.setNoAkaunDari(json.getString("noAkaunDari") != null ? json.getString("noAkaunDari") : null);
                    deposit.setNoKpDari(json.getString("noKPDari") != null ? json.getString("noKPDari") : null);

                    AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);

                    boolean check = checking.checkAcc(deposit, id);

                    if (!check) {
                         return new ErrorResolution(401);
                    }

                    String idSessi = getContext().getRequest().getSession().getId();

                    service.inquiryBalance(deposit, checking.getPengguna(), status, idSessi);

                    return new StreamingResolution("application/json", toJson());
               }

          } catch (IOException e) {
               LOG.error(e);

          } finally {
               try {
                    if (reader != null) {
                         reader.close();
                    }
               } catch (IOException ex) {
               }
          }

          return new ErrorResolution(401);
     }

     @HandlesEvent("req_all_akauns")
     public Resolution getAllAkauns() {

          String sessionId = getContext().getRequest().getParameter("sessionId");

          String userId = getContext().getRequest().getParameter("userId");

          SessionManager sm = SessionManager.getInstance();

          LoginSession ls = sm.getActiveSessionByUserId(userId);

          if (ls != null && ls.getSessionId().equals(sessionId)) {
               Pengguna pengguna = userManager.findUserByIdUser(userId);
               if (pengguna != null) {
                    return new StreamingResolution("application/json",
                            toJsonList(pengguna.getSenaraiAkaun()));
               }
          }

          return new ErrorResolution(401, "Tiada Akaun");
     }

     @HandlesEvent("req_noKp")
     public Resolution getNoKP() {

          String sessionId = getContext().getRequest().getParameter("sessionId");

          String userId = getContext().getRequest().getParameter("userId");

          String noAkaun = getContext().getRequest().getParameter("noAkaun");

          SessionManager sm = SessionManager.getInstance();

          LoginSession ls = sm.getActiveSessionByUserId(userId);

          if (ls != null && ls.getSessionId().equals(sessionId)) {
               String noKP = akaunManager.getNoPengenalan(noAkaun);
               if (StringUtils.isNotBlank(noKP)) {
                    JSONObject obj = new JSONObject();
                    obj.put("noKP", noKP);
                    return new StreamingResolution("application/json", obj.toString());
               }
          }

          return new ErrorResolution(401, "Tiada No KP");
     }

     @HandlesEvent("transfer_step1")
     public Resolution transferStep1() {

          String line = null;

          StringBuilder sb = new StringBuilder();

          String id = getContext().getRequest().getHeader("Cookie");
          id = id.substring(id.indexOf("=") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    Pengguna pengguna = userManager.findUserByIdUser(id);

                    JSONObject json = new org.json.JSONObject(sb.toString());

                    deposit = new Deposit();
                    deposit.setNoAkaun(json.getString("noAkaun") != null ? json.getString("noAkaun") : null);
                    deposit.setNoKp(json.getString("noKP") != null ? json.getString("noKP") : null);
                    deposit.setNoAkaunDari(json.getString("noAkaunDari") != null ? json.getString("noAkaunDari") : null);
                    deposit.setNoKpDari(json.getString("noKPDari") != null ? json.getString("noKPDari") : null);
                    deposit.setNoAkaunPenerima(json.getString("noAkaunPenerima") != null
                            ? json.getString("noAkaunPenerima") : null);
                    String amaun = json.getString("amaun") != null ? json.getString("amaun") : null;
                    if (amaun != null) {
                         deposit.setAmaun(new BigDecimal(amaun));
                    }

                    getContext().setCurrentUser(pengguna);
                    TransferDepositAction action = ableContextListener.newInstance(TransferDepositAction.class);
                    action.setContext(context);
                    action.setPengguna(pengguna);
                    action.setDeposit(deposit);
                    action.selectAmount();

                    ValidationErrors errors = context.getValidationErrors();
                    Locale locale = context.getLocale();
                    for (List<ValidationError> errorList : errors.values()) {
                         for (ValidationError error : errorList) {
                              return new StreamingResolution("text/plain", error.getMessage(locale));
                         }
                    }
               }

          } catch (IOException ex) {
               return new StreamingResolution("text/plain", ex.getLocalizedMessage());
          }

          return new StreamingResolution("application/json", toJson());
     }

     @HandlesEvent("transfer_step2")
     public Resolution transferStep2() {

          String line = null;

          String m_error = "";

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {
                         JSONObject json = new org.json.JSONObject(sb.toString());
                         Pengguna pengguna = userManager.findUserByIdUser(userId);
                         String tac = json.getString("tac") != null ? json.getString("tac") : null;

                         KodKebenaranTransaksi kodKebenaranTransaksi
                                 = sMSgatewayManager.findKodKebenaranTransaksiBySessionId(sessionId, HEADER_ID_FND_TFR, "Y");

                         if (kodKebenaranTransaksi != null) {
                              if (kodKebenaranTransaksi.getSah().equals("Y")
                                      && kodKebenaranTransaksi.getKodKebenaranTransaksi().equals(tac)) {
                                   InfoAudit ia = new InfoAudit();
                                   ia.setDimasukOleh(pengguna);
                                   ia.setTarikhMasuk(new Date());
                                   kodKebenaranTransaksi.setInfoAudit(ia);
                                   kodKebenaranTransaksi.setSah("N");
                                   sMSgatewayManager.saveTAC(kodKebenaranTransaksi);
                              }else {
                                   m_error = "KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH.";
                              }
                         } else {
                              m_error = "KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH.";

                         }

                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }

               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", toJson());
          }
     }

     @HandlesEvent("transfer_step3")
     public Resolution transferStep3() {

          String line = null;

          StringBuilder sb = new StringBuilder();

          String id = getContext().getRequest().getHeader("Cookie");
          id = id.substring(id.indexOf("=") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    Pengguna pengguna = userManager.findUserByIdUser(id);

                    JSONObject json = new org.json.JSONObject(sb.toString());

                    deposit = new Deposit();
                    deposit.setNoAkaun(json.getString("noAkaun") != null ? json.getString("noAkaun") : null);
                    deposit.setNoKp(json.getString("noKP") != null ? json.getString("noKP") : null);
                    deposit.setNoAkaunDari(json.getString("noAkaunDari") != null ? json.getString("noAkaunDari") : null);
                    deposit.setNoKpDari(json.getString("noKPDari") != null ? json.getString("noKPDari") : null);
                    deposit.setNoAkaunPenerima(json.getString("noAkaunPenerima") != null
                            ? json.getString("noAkaunPenerima") : null);
                    String amaun = json.getString("amaun") != null ? json.getString("amaun") : null;
                    if (amaun != null) {
                         deposit.setAmaun(new BigDecimal(amaun));
                    }

                    getContext().setCurrentUser(pengguna);
                    TransferDepositAction action = ableContextListener.newInstance(TransferDepositAction.class);
                    action.setContext(context);
                    action.setPengguna(pengguna);
                    action.setDeposit(deposit);
                    action.completeTransfer();

                    ValidationErrors errors = context.getValidationErrors();
                    Locale locale = context.getLocale();
                    for (List<ValidationError> errorList : errors.values()) {
                         for (ValidationError error : errorList) {
                              return new StreamingResolution("text/plain", error.getMessage(locale));
                         }
                    }
               }

          } catch (IOException ex) {
               return new StreamingResolution("text/plain", ex.getLocalizedMessage());
          }

          return new StreamingResolution("application/json", toJson());
     }
     
     @HandlesEvent("acc_statement")
    public Resolution accountStatement() {

//        LOG.debug("requestEntity : " +  deposit != null ? deposit.getNoAkaun(): "null" );      
        String line = null;
        
        StringBuilder sb = new StringBuilder();
        
        String id = getContext().getRequest().getHeader("Cookie");    
        id = id.substring(id.indexOf("=")+1);
        
        BufferedReader reader = null;
        try {
            
            reader = getContext().getRequest().getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            if (sb.length() > 0) {
                JSONObject json = new org.json.JSONObject(sb.toString());
                
                deposit = new Deposit();
                deposit.setNoAkaun      (   json.getString("noAkaun")       != null ?  json.getString("noAkaun")        : null  );
                
                deposit.setNoKp         (   json.getString("noKP")          != null ?  json.getString("noKP")           : null  );
                
                deposit.setNoAkaunDari  (   json.getString("noAkaunDari")   != null ?  json.getString("noAkaunDari")    : null  );
                
                deposit.setNoKpDari     (   json.getString("noKPDari")      != null ?  json.getString("noKPDari")       : null  );
                
                deposit.setBulanPilihan (   json.getString("bulanPilihan")  != null ?  json.getString("bulanPilihan")   : null  );
                DepositService service = ableContextListener.newInstance(DepositService.class);
                 AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
        
                 boolean check = checking.checkAcc(deposit, id);
                 
                 if (!check) {
                     return new ErrorResolution(401);
                 }                
                
                String idSessi = getContext().getRequest().getSession().getId();
                
                String m_error=service.accountStatement(deposit, checking.getPengguna(), status, idSessi);
                
                if (!("0000").equals(m_error)) {
                return new StreamingResolution("text/plain", "Tiada Senarai Transaksi");
                    } 
                
                else {
               
                return new StreamingResolution("application/json", toJsonACC());}
            }
            
            
        } catch (IOException e) { 
            LOG.error(e);
            
        }finally{
            try {
                if (reader != null) reader.close();
            } catch (IOException ex) {
            }
        }

        return new ErrorResolution(401);
    }

     @HandlesEvent("req_akaun_fav")
     public Resolution getAkaunFav() {

          JSONArray result = new JSONArray();

          String sessionId = getContext().getRequest().getParameter("sessionId");

          String userId = getContext().getRequest().getParameter("userId");

//          String noAkaun = getContext().getRequest().getParameter("noAkaun");
          SessionManager sm = SessionManager.getInstance();

          LoginSession ls = sm.getActiveSessionByUserId(userId);

          if (ls != null && ls.getSessionId().equals(sessionId)) {
               Pengguna pengguna = userManager.findUserByIdUser(userId);
               if (pengguna != null) {
                    List<AkaunFav> senaraiAkaunFav = pengguna.getSenaraiAkaunFav();
                    for (AkaunFav fav : senaraiAkaunFav) {
                         JSONObject obj = new JSONObject();
                         obj.put("noAkaunFav", fav.getNoAkaunFav());
                         obj.put("namaSamaran", fav.getNicknameFav());
                         result.put(obj);
                    }
               }
          }

          return new StreamingResolution("application/json", result.toString());
     }

     @HandlesEvent("iDebit_enq")
     public Resolution iDebitStatmentEnquiry() {

          String line = null;

          String m_error = "";

          JSONObject data = new JSONObject();

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {
                         JSONObject json = new org.json.JSONObject(sb.toString());

                         DepositActionBean action = ableContextListener.newInstance(DepositActionBean.class);

                         deposit = new Deposit();
                         deposit.setNoAkaun(json.getString("noAkaun") != null ? json.getString("noAkaun") : null);
                         deposit.setNoKp(json.getString("noKP") != null ? json.getString("noKP") : null);
                         deposit.setNoAkaunDari(json.getString("noAkaunDari") != null ? json.getString("noAkaunDari") : null);
                         deposit.setNoKpDari(json.getString("noKPDari") != null ? json.getString("noKPDari") : null);
                         deposit.setBulanPilihan(json.getString("bulan") != null ? json.getString("bulan") : null);

                         Pengguna pengguna = userManager.findUserByIdUser(userId);
                         getContext().setCurrentUser(pengguna);
                         action.setContext(context);
                         action.setPengguna(pengguna);
                         action.setDeposit(deposit);
                         action.getPenyataKad();

                         ValidationErrors errors = context.getValidationErrors();
                         Locale locale = context.getLocale();
                         for (List<ValidationError> errorList : errors.values()) {
                              for (ValidationError error : errorList) {
                                   return new StreamingResolution("text/plain", error.getMessage(locale));
                              }
                         }

                         JSONArray array = new JSONArray();
                         List<PenyataKad> senarai = deposit.getSenaraiTransaksiKad();
                         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                         for (PenyataKad kad : senarai) {
                              JSONObject obj = new JSONObject();
                              obj.put("trhTrans", kad.getTarikhTransaksi() != null ? sdf.format(kad.getTarikhTransaksi()) : "");
                              obj.put("trhTerima", kad.getTarikhTerima() != null ? sdf.format(kad.getTarikhTerima()) : "");
                              obj.put("butiran", kad.getButiran() != null ? kad.getButiran() : "");
                              obj.put("amtDebit", kad.getAmaunDebit() != null ? kad.getAmaunDebit().toPlainString() : "");
                              obj.put("amtKredit", kad.getAmaunKredit() != null ? kad.getAmaunKredit().toPlainString() : "");
                              array.put(obj);
                         }

                         data.put("txn", array);
                         data.put("nama", deposit.getNama() != null ? deposit.getNama() : "");
                         data.put("noAkaun", deposit.getNoAkaun() != null ? deposit.getNoAkaun() : "");
                         data.put("noKp", deposit.getNoKp() != null ? deposit.getNoKp() : "");
                         data.put("noKad", deposit.getNoKad() != null ? deposit.getNoKad() : "");
                         data.put("alamat1", deposit.getAlamat1() != null ? deposit.getAlamat1() : "");
                         data.put("alamat2", deposit.getAlamat2() != null ? deposit.getAlamat2() : "");
                         data.put("alamat3", deposit.getAlamat3() != null ? deposit.getAlamat3() : "");
                         data.put("poskod", deposit.getPoskod() != null ? deposit.getPoskod() : "");
                         data.put("negeri", deposit.getNegeriDesc() != null ? deposit.getNegeriDesc() : "");
                         data.put("bulan", deposit.getBulanPilihan() != null ? deposit.getBulanPilihan() : "");

                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }

               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", data.toString());
          }
     }

     @HandlesEvent("add_acc")
     public Resolution addNewAccount() {

          String line = null;

          String m_error = "";

          JSONObject data = new JSONObject();

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {
                         JSONObject json = new org.json.JSONObject(sb.toString());

                         DepositActionBean action = ableContextListener.newInstance(DepositActionBean.class);

                         deposit = new Deposit();
                         Akaun akaun = new Akaun();
                         deposit.setJenisAkaun(json.getString("jenisAcc") != null ? json.getString("jenisAcc") : null);
                         akaun.setAkaunTmbhn(json.getString("noAkaunTmbh") != null ? json.getString("noAkaunTmbh") : null);
                         akaun.setNoPengenalanTmbhn(json.getString("noPengenalanTmbh") != null ? json.getString("noPengenalanTmbh") : null);

                         Pengguna pengguna = userManager.findUserByIdUser(userId);
                         getContext().setCurrentUser(pengguna);
                         action.setContext(context);
                         action.setPengguna(pengguna);
                         action.setDeposit(deposit);
                         action.setAkaun(akaun);
                         action.addAcc();

                         ValidationErrors errors = context.getValidationErrors();
                         Locale locale = context.getLocale();
                         for (List<ValidationError> errorList : errors.values()) {
                              for (ValidationError error : errorList) {
                                   return new StreamingResolution("text/plain", error.getMessage(locale));
                              }
                         }
                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }
               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", data.toString());
          }
     }

     @HandlesEvent("delete_acc")
     public Resolution deleteAccount() {

          String line = null;

          String m_error = "";

          JSONObject data = new JSONObject();

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {
                         JSONObject json = new org.json.JSONObject(sb.toString());

                         String noAkaun = json.getString("noAkaun") != null ? json.getString("noAkaun") : "";
                         if (StringUtils.isNotBlank(noAkaun)) {
                              akaunManager.deleteAkaun(noAkaun);
                         } else {
                              m_error = "No Akaun tiada.";
                         }

                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }
               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", data.toString());
          }
     }

     @HandlesEvent("enq_fav_acc")
     public Resolution enquiryFavAcc() {

          String line = null;

          String m_error = "";

          JSONObject data = new JSONObject();

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {
                         JSONObject json = new org.json.JSONObject(sb.toString());

                         DepositActionBean action = ableContextListener.newInstance(DepositActionBean.class);

                         deposit = new Deposit();
                         deposit.setNoAkaunFav(json.getString("noAkaunFav") != null ? json.getString("noAkaunFav") : null);
                         deposit.setNicknameAkaunFav(json.getString("nickNameAccFav") != null ? json.getString("nickNameAccFav") : null);

                         Pengguna pengguna = userManager.findUserByIdUser(userId);
                         getContext().setCurrentUser(pengguna);
                         action.setContext(context);
                         action.setPengguna(pengguna);
                         action.setDeposit(deposit);
                         action.showAddFavDetail();

                         ValidationErrors errors = context.getValidationErrors();
                         Locale locale = context.getLocale();
                         for (List<ValidationError> errorList : errors.values()) {
                              for (ValidationError error : errorList) {
                                   return new StreamingResolution("text/plain", error.getMessage(locale));
                              }
                         }

                         data.put("noAkaunFav", deposit.getNoAkaunFav());
                         data.put("nickNameFav", deposit.getNicknameAkaunFav());
                         data.put("statusAkaunFav", deposit.getFavStatusAcc());
                         data.put("typeAkaunFav", deposit.getFavTypeAcc());
                         data.put("passbookFav", deposit.getFavPassbook());
                         data.put("namaAkaunFav", deposit.getNamaAkaunFav());

                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }
               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", data.toString());
          }
     }

     @HandlesEvent("add_fav_acc")
     public Resolution addNewFavAccount() {

          String line = null;

          String m_error = "";

          JSONObject data = new JSONObject();

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {

                         JSONObject json = new org.json.JSONObject(sb.toString());

                         Pengguna pengguna = userManager.findUserByIdUser(userId);
                         String tac = json.getString("tac") != null ? json.getString("tac") : null;
                         
                         String noAkaunFav = json.getString("noAkaunFav") != null ? json.getString("noAkaunFav") : null;
                         String namakaunFav = json.getString("namakaunFav") != null ? json.getString("namakaunFav") : null;
                         String nickNameAkaunFav = json.getString("nickNameAkaunFav") != null ? json.getString("nickNameAkaunFav") : null;

                         KodKebenaranTransaksi kodKebenaranTransaksi
                                 = sMSgatewayManager.findKodKebenaranTransaksiBySessionId(sessionId, HEADER_ID_FND_TFR, "Y");

                         if (kodKebenaranTransaksi != null) {
                              if (kodKebenaranTransaksi.getSah().equals("Y")
                                      && kodKebenaranTransaksi.getKodKebenaranTransaksi().equals(tac)) {
                                   InfoAudit ia = new InfoAudit();
                                   ia.setDimasukOleh(pengguna);
                                   ia.setTarikhMasuk(new Date());
                                   kodKebenaranTransaksi.setInfoAudit(ia);
                                   kodKebenaranTransaksi.setSah("N");
                                   sMSgatewayManager.saveTAC(kodKebenaranTransaksi);

                                   AkaunFav akaunFav = new AkaunFav();
                                   akaunFav.setNoAkaunFav(noAkaunFav);
                                   akaunFav.setNamaAkaunFav(namakaunFav);
                                   akaunFav.setNicknameFav(nickNameAkaunFav);
                                   akaunFav.setInfoAudit(ia);
                                   akaunFav.setPenggunaFav(pengguna);

                                   akaunFavManager.saveAccountFav(akaunFav);
                              }else {
                                   m_error = "KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH.";
                              }
                         } else {
                              m_error = "KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH.";

                         }
                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }
               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", data.toString());
          }
     }
     
     @HandlesEvent("delete_fav_acc")
     public Resolution deleteFavAccount() {

          String line = null;

          String m_error = "";

          JSONObject data = new JSONObject();

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {
                         JSONObject json = new org.json.JSONObject(sb.toString());

                         String noAkaun = json.getString("noAkaun") != null ? json.getString("noAkaun") : "";
                         if (StringUtils.isNotBlank(noAkaun)) {
                              akaunFavManager.deleteAkaun(noAkaun);
                         } else {
                              m_error = "No Akaun tiada.";
                         }

                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }
               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", data.toString());
          }
     }
     
     @HandlesEvent("edit_fav_acc")
     public Resolution editFavAccount() {

          String line = null;

          String m_error = "";

          JSONObject data = new JSONObject();

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {
                         JSONObject json = new org.json.JSONObject(sb.toString());

                         String noAkaun = json.getString("noAkaun") != null ? json.getString("noAkaun") : "";
                         if (StringUtils.isNotBlank(noAkaun)) {
                              AkaunFav fav = akaunFavManager.getAkaunFavByNoAcc(noAkaun);
                              if (fav != null) {
                                   data.put("namaSamaran", fav.getNicknameFav());
                                   data.put("noAkaun", fav.getNoAkaunFav());
                              }
                         } else {
                              m_error = "No Akaun tiada.";
                         }

                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }
               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", data.toString());
          }
     }
     
     @HandlesEvent("add_fav_acc2")
     public Resolution addNewFavAccount2() {

          String line = null;

          String m_error = "";

          JSONObject data = new JSONObject();

          StringBuilder sb = new StringBuilder();

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));

          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          BufferedReader reader = null;
          try {

               reader = getContext().getRequest().getReader();
               while ((line = reader.readLine()) != null) {
                    sb.append(line);
               }

               if (sb.length() > 0) {

                    SessionManager sm = SessionManager.getInstance();

                    LoginSession ls = sm.getActiveSessionByUserId(userId);

                    if (ls != null && ls.getSessionId().equals(sessionId)) {

                         JSONObject json = new org.json.JSONObject(sb.toString());

                         Pengguna pengguna = userManager.findUserByIdUser(userId);
                         String tac = json.getString("tac") != null ? json.getString("tac") : null;
                         
                         String noAkaunFav = json.getString("noAkaunFav") != null ? json.getString("noAkaunFav") : null;                         
                         String nickNameAkaunFav = json.getString("nickNameAkaunFav") != null ? json.getString("nickNameAkaunFav") : null;

                         KodKebenaranTransaksi kodKebenaranTransaksi
                                 = sMSgatewayManager.findKodKebenaranTransaksiBySessionId(sessionId, HEADER_ID_FND_TFR, "Y");

                         if (kodKebenaranTransaksi != null) {
                              if (kodKebenaranTransaksi.getSah().equals("Y")
                                      && kodKebenaranTransaksi.getKodKebenaranTransaksi().equals(tac)) {
                                   InfoAudit ia = new InfoAudit();
                                   ia.setDimasukOleh(pengguna);
                                   ia.setTarikhMasuk(new Date());
                                   kodKebenaranTransaksi.setInfoAudit(ia);
                                   kodKebenaranTransaksi.setSah("N");
                                   sMSgatewayManager.saveTAC(kodKebenaranTransaksi);

                                   AkaunFav fav = new AkaunFav();
                                   fav.setNoAkaunFav(noAkaunFav);
                                   fav.setNicknameFav(nickNameAkaunFav);

                                   akaunFavManager.updateAccFavByNoAcc(fav);
                              } else {
                                   m_error = "KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH.";
                              }
                         } else {
                              m_error = "KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH.";

                         }
                    } else {
                         m_error = "ID Sessi TIDAK SAH.";
                    }
               }

          } catch (IOException ex) {
               m_error = ex.getLocalizedMessage();
          }

          if (!("").equals(m_error)) {
               return new StreamingResolution("text/plain", m_error);
          } else {
               return new StreamingResolution("aplication/json", data.toString());
          }
     }

     public String toJson() {

          SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

          JSONObject obj = new JSONObject();
          if (deposit != null) {
               obj.put("noAkaun", deposit.getNoAkaun() != null ? deposit.getNoAkaun() : "");
               if (deposit.getBalanceAmaun() != null) {
                    obj.put("baki", deposit.getBalanceAmaun() != null ? deposit.getBalanceAmaun().toPlainString() : "0.00");
               } else {
                    obj.put("baki", deposit.getBaki() != null ? deposit.getBaki().toPlainString() : "0.00");
               }
               obj.put("noKP", deposit.getNoKp() != null ? deposit.getNoKp() : "");
               obj.put("namaPenerima", deposit.getNamaPenerima() != null ? deposit.getNamaPenerima() : "");
               obj.put("noAkaunPenerima", deposit.getNoAkaunPenerima() != null ? deposit.getNoAkaunPenerima() : "");
               obj.put("amaun", deposit.getAmaun() != null ? deposit.getAmaun().toPlainString() : "0.00");
               obj.put("nama", deposit.getNama() != null ? deposit.getNama() : "");
               obj.put("noResit", StringUtils.isNotBlank(deposit.getNoResit()) ? deposit.getNoResit() : "");
               obj.put("status", StringUtils.isNotBlank(deposit.getStsPindahanDis()) ? deposit.getStsPindahanDis() : "");
               obj.put("trhTransaksi", deposit.getTarikhTransaksi() != null ? dateFormat.format(deposit.getTarikhTransaksi()) : "");
          }
          return obj.toString();
     }
     
     public String toJsonUpProfile() {
        
        
        JSONObject obj = new JSONObject();
    
        obj.put("noAkaun", deposit.getNoAkaun()               !=null   ?   deposit.getNoAkaun()               : null);
        obj.put("noKP"   , deposit.getNoKp()                  !=null   ?   deposit.getNoKp()                  : null);
        obj.put("baki"   , deposit.getBaki()                  !=null   ?   deposit.getBaki().toPlainString()  : null);  
        obj.put("nama"   , deposit.getNama()                  !=null   ?   deposit.getNama()                  : null);
        obj.put("email"  , deposit.getEmail()                 !=null   ?   deposit.getEmail()                 : null);
        obj.put("namaIbu", deposit.getNamaDatuk()             !=null   ?   deposit.getNamaDatuk()             : null);
        obj.put("alamat1", deposit.getAlamat1()               !=null   ?   deposit.getAlamat1()               : null);
        obj.put("alamat2", deposit.getAlamat2()               !=null   ?   deposit.getAlamat2()               : null);
        obj.put("alamat3", deposit.getAlamat3()               !=null   ?   deposit.getAlamat3()               : null);
        //obj.put("alamat4", deposit.getAlamat4()     !=null   ?   deposit.getAlamat4()               : null);
        obj.put("poskod" , deposit.getPoskod()                !=null   ?   deposit.getPoskod()                : null);
        obj.put("noTel1" , deposit.getNoTel1()                !=null   ?   deposit.getNoTel1()                : null);
        obj.put("noTel2" , deposit.getNoTel2()                !=null   ?   deposit.getNoTel2()                : null);
        obj.put("noTel3" , deposit.getNoTel3()                !=null   ?   deposit.getNoTel3()                : null);
        
        obj.put("jantina", deposit.getJantina()               !=null   ?   deposit.getJantina().getNama()     : null);
        obj.put("jantinaKod", deposit.getJantina()            !=null   ?   deposit.getJantina().getKod()     : null);
        
        obj.put("warga"  , deposit.getWarganegara()           !=null   ?   deposit.getWarganegara().getNama() : null);
        obj.put("wargaKod"  , deposit.getWarganegara()        !=null   ?   deposit.getWarganegara().getKod() : null);
        
        obj.put("tLahir" , deposit.getTarikhLahir()           !=null   ?   deposit.getTarikhLahir()           : null);
        obj.put("tLahirFull" , deposit.getTarikhLahir()       !=null   ?   deposit.getTarikhLahir().toString()           : null);
        
        obj.put("kahwin" , deposit.getKahwin()                !=null   ?   deposit.getKahwin().getKod().toString() : null);
        obj.put("negeri" , deposit.getNegeri()                !=null   ?   deposit.getNegeri().getCode().toString() : null);
        obj.put("kerja"  , deposit.getSektorPekerjaan()       !=null   ?   deposit.getSektorPekerjaan().getKod().toString() : null);
        obj.put("bangsa" , deposit.getBangsa()                !=null   ?   deposit.getBangsa()                : null);   

        return obj.toString();
    }
    

     public String toJsonList(List<Akaun> akauns) {
          JSONArray array = new JSONArray();

          for (Akaun akaun : akauns) {
               JSONObject obj = new JSONObject();
               obj.put("akaunTmbhn", akaun.getAkaunTmbhn());
               obj.put("noPengenalanTmbhn", akaun.getNoPengenalanTmbhn());
               obj.put("nama", akaun.getNamaAkaunTmbhn());
               array.put(obj);
          }

          return array.toString();
     }

     public Deposit getDeposit() {
          return deposit;
     }

     public void setDeposit(Deposit deposit) {
          this.deposit = deposit;
     }

    public String toJsonACC() {
        
        
        JSONObject obj = new JSONObject();
    
        obj.put("noAkaun"    , deposit.getNoAkaun()               !=null   ?   deposit.getNoAkaun()               : null);
        obj.put("noKP"       , deposit.getNoKp()                  !=null   ?   deposit.getNoKp()                  : null);
        obj.put("nama"       , deposit.getNama()                  !=null   ?   deposit.getNama()                  : null);
        obj.put("alamat1"    , deposit.getAlamat1()               !=null   ?   deposit.getAlamat1()               : null);
        obj.put("alamat2"    , deposit.getAlamat2()               !=null   ?   deposit.getAlamat2()               : null);
        obj.put("alamat3"    , deposit.getAlamat3()               !=null   ?   deposit.getAlamat3()               : null);
        obj.put("negeriDesc" , deposit.getPoskod()                !=null   ?   deposit.getNegeriDesc()            : null);
        
        obj.put("penyata"    , deposit.getSenaraiTransaksiAkaun() !=null   ?   deposit.getSenaraiTransaksiAkaun() : null);
        

          return obj.toString();        
        
             
    }

}
